from PIL import Image, ImageDraw, ImageFont
import os
import math

def load_font(paths, size):
    """依次尝试加载字体"""
    for path in paths:
        if os.path.exists(path):
            try:
                return ImageFont.truetype(path, size)
            except Exception:
                continue
    return None


def can_render(char, font, verbose=False):
    """判断字体能否渲染指定字符"""
    try:
        bbox = font.getbbox(char)
        width = bbox[2] - bbox[0]
        height = bbox[3] - bbox[1]
        return width > 0 and (height > 0 or char.isspace())
    except Exception:
        return False


def draw_with_fallback(draw, x, y, text, fonts, fill="black"):
    """逐字绘制文本，支持多字体回退"""
    pos_x = x
    for ch in text:
        for font in fonts:
            if can_render(ch, font):
                draw.text((pos_x, y), ch, font=font, fill=fill)
                pos_x += font.getlength(ch)
                break
        else:
            draw.text((pos_x, y), "□", font=fonts[0], fill="gray")
            pos_x += fonts[0].getlength("□")


def wrap_text(text, fonts, max_width):
    """
    自动换行：根据字体宽度将文本拆分成多行
    text: 原始字符串
    fonts: 字体列表
    max_width: 每行允许的最大宽度（像素）
    """
    lines = []
    current_line = ""
    current_width = 0
    font = fonts[0]  # 默认使用第一个字体测量宽度

    for ch in text:
        w = font.getlength(ch)
        if current_width + w > max_width:
            # 超过行宽 -> 换行
            lines.append(current_line)
            current_line = ch
            current_width = w
        else:
            current_line += ch
            current_width += w

    if current_line:
        lines.append(current_line)

    return lines


def main():
    print("请输入要写在图片上的多行文字（输入end over）：")
    lines = []
    while True:
        line = input()
        if line=="end":
            break
        lines.append(line)

    if not lines:
        print("未输入任何文字，程序结束。")
        return

    try:
        defultwidth=670
        defultheight=1100
        width = int(input(f"请输入图片宽度（默认{defultwidth}）：") or defultwidth)
        height = int(input(f"请输入图片高度（默认{defultheight}）：") or defultheight)
    except ValueError:
        width, height = defultwidth, defultheight
    defultImgSaveForder=r"C:\Users\33720\Desktop\temp"
# defultImgSaveForder=os.path.join(os.path.expanduser("~"), "Desktop")
    # output_dir = input("请输入输出文件夹路径,默认位置:{defultImgSaveForder}：") or defultImgSaveForder
    output_dir = input(f"请输入输出文件夹路径,默认为{defultImgSaveForder}：") or defultImgSaveForder
    os.makedirs(output_dir, exist_ok=True)

    # 字体路径
    font_paths_yahei = [
        "C:\\Windows\\Fonts\\msyh.ttc",
        "C:\\Windows\\Fonts\\msyhbd.ttc"
    ]

    font_paths_yu = [
        "C:\\Windows\\Fonts\\YuGothM.ttc",
        "C:\\Windows\\Fonts\\YuGothB.ttc"
    ]

    # 加载字体
    font_size = 25
    font_yu = load_font(font_paths_yu, font_size)
    font_yahei = load_font(font_paths_yahei, font_size)
    fonts = [f for f in [font_yahei, font_yu] if f]

    if not fonts:
        print("⚠️ 未找到可用字体，请检查字体路径！")
        return

    # 每张图片最多显示 20 行
    lines_per_image = 25
    total_images = math.ceil(len(lines) / lines_per_image)
    id=0
    for idx in range(total_images):
        start = idx * lines_per_image
        end = start + lines_per_image
        chunk = lines[start:end]

        img = Image.new("RGB", (width, height), color="white")
        draw = ImageDraw.Draw(img)

        # 每行高度
        line_height = fonts[0].getbbox("あ")[3] + 10
        start_y = 40
        left_x = 40
        usable_width = width - left_x * 2  # 可用宽度

        y = start_y
        for text in chunk:
            if text.strip() == "":
                # 如果是空行，则只增加行高，不绘制文字
                y += line_height
                continue

            wrapped_lines = wrap_text(text, fonts, usable_width)
            for wrapped_line in wrapped_lines:
                draw_with_fallback(draw, left_x, y, wrapped_line, fonts)
                y += line_height

                # ✅ 保存图片（新增部分）
        output_path = os.path.join(output_dir, f"{id:02d}.jpg")
        id += 1
        img.save(output_path)
        print(f"✅ 已生成：{output_path}")


    print(f"\n🎉 共生成 {total_images} 张图片，保存至：{os.path.abspath(output_dir)}")


if __name__ == "__main__":
    main()
